//
//  SecurityMessageFmdbModel.m
//  LocomotiveGuards
//
//  Created by xys on 15/12/22.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "SecurityMessageFmdbModel.h"
#import "FMDatabase.h"

@interface SecurityMessageFmdbModel ()
{
    FMDatabase *db;
    NSString * tableName;
}

@end
@implementation SecurityMessageFmdbModel

- (instancetype) init
{
    if (self = [super init])
    {
        NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"securityMessages.db"];
        db     = [FMDatabase databaseWithPath:dbPath];
        [db open];
        tableName = [[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
        if (tableName && ![tableName isEqualToString:@""])
        {
            tableName = [NSString stringWithFormat:@"t%@",tableName];
            [db executeUpdate:[NSString stringWithFormat:@"create table %@ (msgId text, msg text, time integer, type text, isDelete text)",tableName]];
        }
    }
    
    return self;
}

/**
 *  获取所有消息
 *
 *  @return 消息列表
 */
- (NSArray *)messages
{
    NSMutableArray * messagesList = nil;
    
    messagesList = [[NSMutableArray alloc]init];
    
    FMResultSet *rs = [db executeQuery:[NSString stringWithFormat:@"select rowid,* from %@ order by time desc",tableName]];
    while ([rs next])
    {
        if ([[rs stringForColumn:@"isDelete"] isEqualToString:@"0"])
        {
            [messagesList addObject:@{@"msg":[rs stringForColumn:@"msg"],
                                      @"time":[NSString stringWithFormat:@"%lld",[rs longLongIntForColumn:@"time"]],
                                      @"type":[rs stringForColumn:@"type"],
                                      @"msgId":[rs stringForColumn:@"msgId"]}];
        }
    }
    [rs close];
    
    return messagesList;
}

/**
 *  判断消息是否存在
 *
 *  @param msgId 消息id
 */
- (BOOL)messageIsExist:(NSString *) msgId
{
    if (!msgId || [msgId isEqualToString:@""])
    {
        return NO;
    }
    
    FMResultSet *rs = [db executeQuery:[NSString stringWithFormat:@"select rowid, msgId from %@ where msgId = %@",tableName,msgId]];
    if ([rs next])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

/**
 *  插入消息
 *
 *  @param msgList 消息列表
 */
- (void)insertMessages:(NSArray *) msgList
{
    [db beginTransaction];
    for (int loop = 0; loop < msgList.count; loop++)
    {
        NSDictionary * msgDict = msgList[loop];
        NSString * msgId = [msgDict objectForKey:@"msgId"];
        if (msgId && ![msgId isEqualToString:@""])
        {
            if (![self messageIsExist:msgId])
            {
                [db executeUpdate:[NSString stringWithFormat:@"insert into %@ (msgId, msg, time, type, isDelete) values (?, ?, ?, ?, ?)",tableName],msgId,msgDict[@"msg"],msgDict[@"time"],msgDict[@"type"],@"0"];
                self.lastMessage = msgDict;
            }
        }
    }
    [db commit];
}

/**
 *  删除消息:仅标记消息为删除状态
 *
 *  @param msgIdList 消息索引列表
 */
- (void)deleteMessages:(NSArray *) msgIdList
{
    [db beginTransaction];
    for (int loop = 0; loop < msgIdList.count; loop++)
    {
        NSString * msgId = msgIdList[loop];
        
        if (msgId && ![msgId isEqualToString:@""])
        {
            [db executeUpdate:[NSString stringWithFormat:@"UPDATE %@ SET isDelete = %@ WHERE msgId = %@",tableName,@"1",msgId]];
        }
    }
    [db commit];
}

- (void)dealloc
{
    [db close];
}

@end
